define(['jquery', 'bootstrap', 'backend', 'table', 'form', '/assets/addons/kuerp/layui/layui.js'], function ($, undefined, Backend, Table, Form, Layui) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'examine/expense/index' + location.search,
                    add_url: 'examine/expense/add',
                    edit_url: 'examine/expense/edit',
                    del_url: 'examine/expense/del',
                    multi_url: 'examine/expense/multi',
                    import_url: 'examine/expense/import',
                    table: 'examine_expense',
                }
            });

            var table = $("#table");
            var admin_id = Config.admin_id;
            var adminlist = Config.adminlist;

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                columns: [
                    [
                        // {checkbox: true},
                        // {field: 'id', title: __('Id')},
                        {field: 'expense_code', title: __('Expense_code'), operate: 'LIKE'},
                        {field: 'admin_id', title: __('Admin_id'), formatter:Table.api.formatter.label,searchList:adminlist},
                        {field: 'cost', title: __('Cost'), operate:'BETWEEN'},
                        {field: 'income_month', title: __('Income_month'), operate:'eq', addclass:'datetimepicker',data:'data-date-format="YYYY-MM"', formatter: Table.api.formatter.datetime,datetimeFormat:'YYYY-MM'},
                        {field: 'start_time', title: __('Start_time'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: function(value, row, index) {
                            return row.start_time_text;
                        }},
                        {field: 'end_time', title: __('End_time'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: function(value, row, index) {
                            return row.end_time_text;
                        }},
                        
                        // {field: 'did', title: __('Did')},
                        {field: 'pay_status', title: __('Pay_status'),operate:false,formatter:Table.api.formatter.status,searchList:{"0":__('Pay_status 0'),"1":__('Pay_status 1')}},
                        // {field: 'remark', title: __('Remark'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        // {field: 'last_checkadmin', title: __('最后审核人'), formatter: function(value, row, index){
                        //     return row.last_checkadmin && (row.last_checkadmin.nickname || '')
                        // }},
                        {field: 'check_status', title: __('Check_status'),formatter:Table.api.formatter.status,custom:{"0":"", "1":"info", "2":"success", "3":"danger", "4":"info"},searchList:{"0":__('Check_status 0'),"1":__('Check_status 1'),"2":__('Check_status 2'),"3":__('Check_status 3'),"4":__('Check_status 4')}},
                        {field: 'createtime', title: __('Create_time'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'detail',
                                    text: __(''),
                                    title: '详情',
                                    classname: 'btn btn-xs btn-info  btn-dialog',
                                    icon: 'fa fa-file-o',
                                    url: function (row, column) { //row 表格接收到的数据
                                        return "examine/expense/detail?ids=" + row.id; //弹窗的对应后台控制器方法 这里是默认index方法 加id参数
                                    },
                                    extend: 'data-area=\'["90%","90%"]\'',
                                    refresh: true
                                }
                            ],
                            formatter: Table.api.formatter.operate}
                    ]
                ]
            });
            //当表格数据加载完成时
            table.on('load-success.bs.table', function (e, data) {
                //这里可以获取从服务端获取的JSON数据
                console.log(data);
                //这里我们手动设置底部的值
                $("#money").text(data.extend.total_cost);
            });
            //tab 切换
            // $('#check_status li a').on('click', function () {
            //     setTimeout(() => {
            //         table.reload('table');
            //     }, 0);
                
            // });
            
            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        detail: function () {
            //审核提交
            $(document).on('click', '.layer-footer .btn', function() {
                var type = $(this).data('value')
                console.log('type', type)
                if (type == 1) {
                    layer.confirm('确认审核通过？',{icon: 3, title:'提示'}, function(index){
                        //do something
                        examineSubmit(1)
                        layer.close(index);
                      });  
                } else {
                    var html='<div class="form-group">'+
                        '<label class="control-label col-xs-12 col-sm-3">审核备注：</label>'+
                        '<div class="col-xs-12 col-sm-9">'+
                        '<textarea class="form-control" name="remark" id="examine_remark" rows="5"></textarea>'+
                        '</div>'+
                       '</div>';
                    layer.open({
                        title: '审核不通过',
                        content: html,
                        area: ['50%', '50%'],
                        yes: function(index, layero){
                            var remark = $("#examine_remark").val();
                            if (!remark) {
                                layer.msg('请输入审核备注！')
                                return false
                            }
                            examineSubmit(0)
                            layer.close(index); //如果设定了yes回调，需进行手工关闭
                        }
                      }); 
                }
                return false
            })

            function examineSubmit(status) {
                var remark = $("#examine_remark").val();
                var id = $("#ids").val();
                $.ajax({
                    url: "examine/expense/examine?ids="+id,
                    type: "POST",
                    data:{
                        'id':id,
                        'remark':remark,
                        'status':status,
                    },
                    success:function(res){
                        if(res.code==1){
                            reloadStatus = true
                            parent.location.reload();
                        }else{
                            layer.msg(res.msg, {icon: 2})
                        }
                        // layer.closeAll();
                    }
                })
            }
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                // 绑定表单验证
                Form.api.bindevent($("form[role=form]"));

                $(document).on("fa.event.appendfieldlist", '.fieldlist', function(){
                    //通用的表单组件事件绑定和组件渲染
                    Form.events.selectpage($("form"));
                    Form.events.datetimepicker($("form"));
                });

                 // 监听删除行按钮点击事件
                 $(document).on("click", ".btn-remove", function(){
                    // 等待DOM更新完成后再计算总计
                    setTimeout(function(){
                        // 计算所有行的总计
                        var grandTotal = 0;
                        $('input[name$="[total_money]"]').each(function(){
                            var value = parseFloat($(this).val()) || 0;
                            grandTotal += value;
                        });
                        
                        // 更新显示
                        $('#total_money').text(grandTotal.toFixed(2));
                        var chineseAmount = numberToChinese(grandTotal);
                        $('#total_money_chinese').text(chineseAmount);
                    }, 100);
                });

                // 监听费用输入变化
                $(document).on("change keyup", ".fee", function(){
                    var $this = $(this);
                    var $row = $this.closest('tr');
                    
                    // 计算当前行的合计
                    var rowTotal = 0;
                    $row.find('.fee').each(function(){
                        var value = parseFloat($(this).val()) || 0;
                        rowTotal += value;
                    });
                    
                    // 更新当前行的合计
                    $row.find('input[name$="[total_money]"]').val(rowTotal.toFixed(2));
                    
                    // 计算所有行的总计
                    var grandTotal = 0;
                    $('input[name$="[total_money]"]').each(function(){
                        var value = parseFloat($(this).val()) || 0;
                        grandTotal += value;
                    });
                    
                    // 更新总费用到隐藏字段（如果需要）
                    $('#c-total_money').val(grandTotal.toFixed(2));
                    
                    // 可选：显示大写金额
                    var chineseAmount = numberToChinese(grandTotal);
                    $('#total_money_chinese').text(chineseAmount);
                    $('#total_money').text(grandTotal.toFixed(2));
                    // $('#amount-in-words').text('合计金额：' + grandTotal.toFixed(2) + '元(' + chineseAmount + ')');
                });
                $('#total_money_chinese').text(numberToChinese(parseFloat($('#total_money').text())));
                // 数字转中文大写函数
                function numberToChinese(number) {
                    var units = ['', '拾', '佰', '仟', '万', '拾', '佰', '仟', '亿'];
                    var chars = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
                    
                    var n = Math.floor(number);
                    var decimals = ((number % 1) * 100).toFixed(0);
                    var chineseStr = '';
                    
                    if (n > 0) {
                        var str = n.toString();
                        for (var i = 0; i < str.length; i++) {
                            var digit = parseInt(str[i]);
                            if (digit === 0) {
                                if (i < str.length - 1 && parseInt(str[i + 1]) !== 0) {
                                    chineseStr += chars[digit];
                                }
                            } else {
                                chineseStr += chars[digit] + units[str.length - 1 - i];
                            }
                        }
                        chineseStr += '元';
                    }
                    
                    
                    
                    if (decimals > 0) {
                        if (n === 0) {
                            chineseStr += '零元';
                        }
                        var jiao = Math.floor(decimals / 10);
                        var fen = decimals % 10;
                        if (jiao > 0) chineseStr += chars[jiao] + '角';
                        if (fen > 0) chineseStr += chars[fen] + '分';
                    } else {
                        if (n > 0) {
                            chineseStr += '整';
                        }
                    }
                    
                    return chineseStr;
                }
            }
        }
    };
    return Controller;
});
